/**
 * @author <a href="mailto:gunn.duncan@gmail.com">Duncan Gunn</a>
 * @version 1.0a
 * */

/** Creates a GridView class.
 * @class Represents a Grid View, providing a wrapper around jQuery DataTable.
 * http://www.datatables.net/
 * */
function GridView() {

  var _gridController;
  var _tableGrid;
  var _gridElement;
  var _rowElement;

}

/**
 * Get property method for the corresponding GridController.
 */
GridView.prototype.getGridController = function () {
    return this._gridController;
}

/**
 * 
 * @param controller The GridController
 * @param gridElement The HTML Element that the GridControl wraps around
 * @param rowClassElement The CSS class for each Row.  This is used to select the rows to bind the edit function.
 * @param rowElement The Prefix for each Row, to allow selection in handleEdit.  Usually the entity name.
 */
GridView.prototype.initialize = function(controller, gridElement, rowClassElement, rowElement){

  this._gridController = controller;
  this._gridElement = gridElement;
  this._rowElement = rowElement;

  //Set up data table
  this._tableGrid = $(this._gridElement).dataTable({
      "bPaginate": false,
      "aaSorting": [[0, "desc"]],
      "bJQueryUI": true
  });

  //bind to Edit actions
  var containingClass = this;
  $(rowClassElement).each(function () {
      $(this).bind("click", createMethodReference(containingClass, "handleEdit"));
    });


}

/**
 * Handle a row edit.
 * @param e Event params
 */
GridView.prototype.handleEdit = function (e) {
    var target = $(e.currentTarget);
    e.returnValue = false;
    e.preventDefault();
    e.stopPropagation();
    var id = $(target).attr('rel');
    //Get table row
    var tr = $(this._rowElement + id)[0];
    var aPos = this._tableGrid.fnGetPosition(tr);

    this.getGridController().editRow(id, aPos);

    return false;
}


/** The GridController class.
 * @class The base grid view class.   */
function GridController(){

    /**@private*/
    var _dialogView;
    /**@private*/
    var _gridView;

    var _editMode = false;
    var _editEntityID = null;
    var _editEntityRowID = null;

    var _createURL = null;
    var _editURL = null;

    var _rowclassElement = null;
    var _tableIDElement = null;

    var _masterEntityID = null;
}

/**
 * Edit Row.  Abstract.
 * @param id
 * @param rowID
 */
GridController.prototype.editRow = function(id, rowID)
{
}

/**
 * Return the HTML for the Edit link for a row.
 * @param entityID The ID of the Entity in the database.
 * @param elementClass The row element class.
 */
GridController.prototype.GetActionLinks = function(entityID, elementClass){
    var link = "<a class='" + elementClass + "' rel='" + entityID + "' href='#'>Edit</a>";
    return link;
}

/**
 * Return the JSON for a new entity.  Abstract.
 * @param id
 */
GridController.prototype.GetNewEntityJSON = function(id) {
}

/**
 * Return the Values for an existing entity.  Abstract.
 */
GridController.prototype.getEntityValues = function(){

}

/**
 * Handles when an entity is saved.  Will create a new entity or edit an existing one, depending on the editMode.
 */
GridController.prototype.Save = function(){
    var container = this;

    if (!this._editMode) {
        $.post(this._createURL, this.GetNewEntityJSON(container._masterEntityID),
        function (newEntityID) {

            var entityVals = container.getEntityValues();
            var tableDataParams = new Array();
            tableDataParams[0] = container.GetActionLinks(newEntityID, container._rowclassElement);
            tableDataParams = tableDataParams.concat(entityVals);

            //Now refresh the table!
            var a = container._gridView._tableGrid.fnAddData(tableDataParams);
            //Attach click event
            //bind to entity list actions
            $('.' + container._rowclassElement + '[rel=' + newEntityID + ']').each(function () {
                $(this).click(function ()
                {
                    container.editRow($(this).attr('rel'), a[0]);
                    return false; });
                });

            //Now must set the ID for the tr!
            var oSettings = container._gridView._tableGrid.fnSettings();
            var nTr = oSettings.aoData[a[0]].nTr;
            $(nTr).attr("id", container._tableIDElement + newEntityID);
        },
            "json");

    }
    else
    {
        $.post(this._editURL + container._editEntityID, this.GetNewEntityJSON(container._editEntityID), null, "json");
        //Now update the table!
         var entityVals = container.getEntityValues();
         var tableDataParams = new Array();
         tableDataParams[0] = container.GetActionLinks(container._editEntityID, container._rowclassElement);
         tableDataParams = tableDataParams.concat(entityVals);

        container._gridView._tableGrid.fnUpdate(tableDataParams, container._editEntityRowID);
        //Bind to entity list action
        $('.' + container._rowclassElement + '[rel=' + container._editEntityID + ']').each(function () {
                $(this).click(function () { container.editRow($(this).attr('rel'), container._editEntityRowID); return false; });
                });
    }

    this.closeDialog();
}

/**
 * Close the edit/create dialog
 */
GridController.prototype.closeDialog = function(){
    this._dialogView.closeDialog();
}

/**
 * Show the edit/create dialog
 */
GridController.prototype.showDialog = function() {
    this._dialogView.show();
}

/**
 * @event
 * Event handler for Cancel edit/add button click.
 */
GridController.prototype.Cancel = function(){
  this._dialogView.closeDialog();
}